{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Title: msticpy - nbwidgets\n",
    "## Description:\n",
    "This contains a few aggregated widgets using IPyWidgets that help speed things up during an investigation.\n",
    "\n",
    "You must have msticpy installed to run this notebook:\n",
    "```\n",
    "%pip install --upgrade msticpy\n",
    "```\n",
    "\n",
    "MSTICpy versions >= 0.8.5"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='contents'></a>\n",
    "## Table of Contents\n",
    "- [Setting query start/end times](#QueryTime)\n",
    "- [Simple time range](#Lookback)\n",
    "- [Selecting and Displaying Alerts](#AlertSelector)\n",
    "- [Selecting from list or dict](#SelectString)\n",
    "- [Getting a value from environment](#GetEnvironmentKey)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-12-19T22:12:36.439490Z",
     "start_time": "2019-12-19T22:12:34.694845Z"
    },
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "# Imports\n",
    "import sys\n",
    "MIN_REQ_PYTHON = (3,6)\n",
    "if sys.version_info < MIN_REQ_PYTHON:\n",
    "    print('Check the Kernel->Change Kernel menu and ensure that Python 3.6')\n",
    "    print('or later is selected as the active kernel.')\n",
    "    sys.exit(\"Python %s.%s or later is required.\\n\" % MIN_REQ_PYTHON)\n",
    "\n",
    "from IPython.display import display, Markdown\n",
    "import pandas as pd\n",
    "\n",
    "from msticpy import nbwidgets\n",
    "from msticpy.nbtools.security_alert import SecurityAlert\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='QueryTime'></a>[Contents](#contents)\n",
    "## QueryTime\n",
    "\n",
    "This widget is used to specify time boundaries - designed to be used with the built-in msticpy queries and custom queries.\n",
    "The `start` and `end` times are exposed as datetime properties.\n",
    "\n",
    "```\n",
    "QueryTime.\n",
    "\n",
    "Composite widget to capture date and time origin\n",
    "and set start and end times for queries.\n",
    "\n",
    "Parameters\n",
    "----------\n",
    "QueryParamProvider : QueryParamProvider\n",
    "    Abstract base class\n",
    "\n",
    "Parameters\n",
    "----------\n",
    "origin_time : datetime, optional\n",
    "    The origin time (the default is `datetime.utcnow()`)\n",
    "label : str, optional\n",
    "    The description to display\n",
    "    (the default is 'Select time ({units}) to look back')\n",
    "before : int, optional\n",
    "    The default number of `units` before the `origin_time`\n",
    "    (the default is 60)\n",
    "after : int, optional\n",
    "    The default number of `units` after the `origin_time`\n",
    "    (the default is 10)\n",
    "max_before : int, optional\n",
    "    The largest value for `before` (the default is 600)\n",
    "max_after : int, optional\n",
    "    The largest value for `after` (the default is 100)\n",
    "units : str, optional\n",
    "    Time unit (the default is 'min')\n",
    "    Permissable values are 'day', 'hour', 'minute', 'second'\n",
    "    These can all be abbreviated down to initial characters\n",
    "    ('d', 'm', etc.)\n",
    "auto_display : bool, optional\n",
    "    Whether to display on instantiation (the default is False)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-12-19T22:12:42.494790Z",
     "start_time": "2019-12-19T22:12:42.453819Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "4a6e2f13719448c3adbae56ec68b6065",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "VBox(children=(HTML(value='<h4>Set query time boundaries</h4>'), HBox(children=(DatePicker(value=datetime.date…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "q_times = nbwidgets.QueryTime(units='day', max_before=20, before=5, max_after=1)\n",
    "q_times.display()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-09-02T23:37:00.573557Z",
     "start_time": "2019-09-02T23:37:00.569561Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2022-03-10 20:30:11.220186 .... 2022-03-16 20:30:11.220186\n"
     ]
    }
   ],
   "source": [
    "print(q_times.start, '....', q_times.end)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Keep multiple query boundaries aligged by having QueryTime instances reference the time of the same alert or event, or have them chained from one another by referencing the origin_time of an earlier QueryTimes object"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-12-19T22:29:50.924729Z",
     "start_time": "2019-12-19T22:29:50.845790Z"
    },
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "c479a26992aa437b953815cae7df1bd1",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "VBox(children=(HTML(value='<h4>Set query time boundaries</h4>'), HBox(children=(DatePicker(value=datetime.date…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "e72dbce1822e436491d1ac4c8ebbc498",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "VBox(children=(HTML(value='<h4>Set query time boundaries</h4>'), HBox(children=(DatePicker(value=datetime.date…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from datetime import datetime, timedelta\n",
    "\n",
    "\n",
    "class MyAlert:\n",
    "    pass\n",
    "\n",
    "alert = MyAlert()\n",
    "alert.TimeGenerated = datetime.utcnow() - timedelta(15)\n",
    "alert.TimeGenerated\n",
    "\n",
    "q_times1 = nbwidgets.QueryTime(units='hour', max_before=20, before=1, max_after=1, \n",
    "                             origin_time=alert.TimeGenerated, auto_display=True)\n",
    "\n",
    "q_times2 = nbwidgets.QueryTime(units='hour', max_before=20, before=4, max_after=2, \n",
    "                             origin_time=alert.TimeGenerated, auto_display=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-12-19T22:29:53.682587Z",
     "start_time": "2019-12-19T22:29:53.608644Z"
    },
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "b10950cd7caa428fbc217a5c909e0ad4",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "VBox(children=(HTML(value='<h4>Set query time boundaries</h4>'), HBox(children=(DatePicker(value=datetime.date…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "c545903af3d3408589fc34bcd23b8f76",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "VBox(children=(HTML(value='<h4>Set query time boundaries</h4>'), HBox(children=(DatePicker(value=datetime.date…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "alert.TimeGenerated = datetime.utcnow()\n",
    "q_times1 = nbwidgets.QueryTime(units='hour', max_before=20, before=1, max_after=1, \n",
    "                             origin_time=alert.TimeGenerated, auto_display=True)\n",
    "\n",
    "q_times2 = nbwidgets.QueryTime(units='hour', max_before=20, before=4, max_after=2, \n",
    "                             origin_time=q_times2.origin_time, auto_display=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-09-02T23:37:04.725203Z",
     "start_time": "2019-09-02T23:37:04.721208Z"
    },
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "SecurityAlert \n",
      "| where TimeGenerated >= datetime(2022-03-15 19:30:11.736218)\n",
      "| where TimeGenerated <= datetime(2022-03-16 02:30:11.736218)\n"
     ]
    }
   ],
   "source": [
    "# Use the values in a query\n",
    "my_kql = f'''\n",
    "SecurityAlert \n",
    "| where TimeGenerated >= datetime({q_times1.start})\n",
    "| where TimeGenerated <= datetime({q_times1.end})'''\n",
    "print(my_kql)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='Lookback'></a>[Contents](#contents)\n",
    "## Lookback\n",
    "Simpler version with single slider value\n",
    "\n",
    "Docstring:\n",
    "`nbwidgets.Lookback?`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-12-19T22:29:59.905261Z",
     "start_time": "2019-12-19T22:29:59.893270Z"
    },
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "9b5b0182c6e341688450c16ce4728124",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "IntSlider(value=6, description='Select time (HOUR) to look back', layout=Layout(height='50px', width='60%'), m…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "alert.TimeGenerated = datetime.utcnow() - timedelta(5)\n",
    "lb = nbwidgets.Lookback(origin_time=alert.TimeGenerated, auto_display=True, max_value=48)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-09-02T23:37:09.268885Z",
     "start_time": "2019-09-02T23:37:09.265888Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2022-03-10 14:30:12.020220 .... 2022-03-10 20:30:12.020220\n"
     ]
    }
   ],
   "source": [
    "print(lb.start, '....', lb.end)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='AlertSelector'></a>[Contents](#contents)\n",
    "## Alert Browser\n",
    "\n",
    "```\n",
    "SelectAlert.\n",
    "\n",
    "View list of alerts and select one for investigation.\n",
    "Optionally provide and action to call with the selected alert as a parameter\n",
    "(typically used to display the alert.)\n",
    "\n",
    "Attributes:\n",
    "    selected_alert: the selected alert\n",
    "    alert_id: the ID of the selected alert\n",
    "    alerts: the current alert list (DataFrame)\n",
    "Init docstring:\n",
    "Create a new instance of AlertSelector.\n",
    "\n",
    "Parameters\n",
    "----------\n",
    "alerts : pd.DataFrame\n",
    "    DataFrame of alerts.\n",
    "action : Callable[..., None], optional\n",
    "    Optional function to execute for each selected alert.\n",
    "    (the default is None)\n",
    "columns : list, optional\n",
    "    Override the default column names to use from `alerts`\n",
    "    (the default is ['StartTimeUtc', 'AlertName',\n",
    "    'CompromisedEntity', 'SystemAlertId'])\n",
    "auto_display : bool, optional\n",
    "    Whether to display on instantiation (the default is False)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Simple alert selector\n",
    "Selected alert is available as `select_alert_widget.selected_alert` property"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-12-19T22:33:01.169572Z",
     "start_time": "2019-12-19T22:33:01.108619Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "### Simple alert selector"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/markdown": [
       "Selected alert is available as `select_alert_widget.selected_alert`"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "8f232775764a4a66abe86df410eeafe1",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "VBox(children=(Text(value='', description='Filter alerts by title:', style=DescriptionStyle(description_width=…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "<hr>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Load test data\n",
    "alerts = pd.read_csv('data/alertlist.csv')\n",
    "\n",
    "display(Markdown('### Simple alert selector'))\n",
    "display(Markdown('Selected alert is available as `select_alert_widget.selected_alert`'))\n",
    "alert_select = nbwidgets.SelectAlert(alerts=alerts)\n",
    "alert_select.display()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Alert selector with action=SecurityAlert'\n",
    "You can pass a function that returns one or more displayable objects.\n",
    "You can also pass a class (in this case we're passing `SecurityAlert`) that produces an IPython displayable object.\n",
    "\n",
    "The `action` class/function is passed the raw alert row as a parameter, as it is selected from the list"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-12-19T22:33:22.044868Z",
     "start_time": "2019-12-19T22:33:21.987913Z"
    }
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "144bc9cf0333451f9fa588cfe2116605",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "VBox(children=(Text(value='', description='Filter alerts by title:', style=DescriptionStyle(description_width=…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "<hr>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "\n",
       "            <h3>Alert: 'DC local group addition - Demo'</h3>\n",
       "            <b>Alert_time:</b> 2019-01-11 06:31:40,\n",
       "            <b>Compr_entity:</b> nan,\n",
       "            <b>Alert_id:</b> self.properties['SystemAlertId']\n",
       "            <table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>0</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Unnamed: 0</th>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>TenantId</th>\n",
       "      <td>802d39e1-9d70-404d-832c-2de5e2478eda</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>StartTimeUtc</th>\n",
       "      <td>2019-01-11 06:31:40</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>EndTimeUtc</th>\n",
       "      <td>2019-01-12 06:31:40</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ProviderAlertId</th>\n",
       "      <td>e0c9484b-ad5f-4161-b73b-388676c05818</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>SystemAlertId</th>\n",
       "      <td>047f47d6-79b7-4502-824b-97abc4905a73</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ProviderName</th>\n",
       "      <td>CustomAlertRule</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>VendorName</th>\n",
       "      <td>Alert Rule</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>AlertType</th>\n",
       "      <td>DC local group addition - Demo</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>AlertName</th>\n",
       "      <td>DC local group addition - Demo</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>AlertDisplayName</th>\n",
       "      <td>DC local group addition - Demo</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Description</th>\n",
       "      <td>Domain controllers local group addition</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Severity</th>\n",
       "      <td>Low</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>IsIncident</th>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ExtendedProperties</th>\n",
       "      <td>{'Alert Mode': 'Aggregated', 'Search Query': '{\"detailBladeInputs\":{\"id\":\"/subscriptions/3c1bb38c-82e3-4f8d-a115-a7110ba70d05/resourcegroups/contoso77/providers/microsoft.operationalinsights/workspaces/contoso77\",\"parameters\":{\"q\":\"SecurityEvent\\n| where EventID == 4625\\n| extend IPCustomEntity = \\\"75.10.91.22\\\"\\n| extend HostCustomEntity = Computer\\n| extend AccountCustomEntity = Account\",\"timeInterval\":{\"intervalDuration\":86400,\"intervalEnd\":\"2019-01-12T06%3A31%3A40.000Z\"}}},\"detailBlade\":\"SearchBlade\",\"displayValue\":\"SecurityEvent\\n| where EventID == 4625\\n| extend IPCustomEntity = \\\"75.10.91.22\\\"\\n| extend HostCustomEntity = Computer\\n| extend AccountCustomEntity = Account\",\"extension\":\"Microsoft_OperationsManagementSuite_Workspace\",\"kind\":\"OpenBlade\"}', 'Search Query Results Overall Count': '23034', 'Threshold Operator': 'Greater Than', 'Threshold Value': '10000', 'Query Interval in Minutes': '1440', 'Suppression in Minutes': '800', 'Total Account Entities': '1563', 'Total IP Entities': '1', 'Total Host Entities': '1'}</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Entities</th>\n",
       "      <td>[{'$id': '3', 'Address': '75.10.91.22', 'Type': 'ip', 'Count': 23034}, {'$id': '4', 'HostName': 'DHCPContoso77', 'Type': 'host', 'Count': 23034}, {'$id': '5', 'Name': 'ADMINISTRATOR', 'NTDomain': '', 'Host': {'$ref': '4'}, 'IsDomainJoined': False, 'Type': 'account', 'Count': 5909}, {'$id': '6', 'Name': 'ADMIN', 'NTDomain': '', 'Host': {'$ref': '4'}, 'IsDomainJoined': False, 'Type': 'account', 'Count': 878}, {'$id': '7', 'Name': 'USER', 'NTDomain': '', 'Host': {'$ref': '4'}, 'IsDomainJoined': False, 'Type': 'account', 'Count': 486}]</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ConfidenceLevel</th>\n",
       "      <td>Unknown</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ConfidenceScore</th>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ExtendedLinks</th>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>WorkspaceSubscriptionId</th>\n",
       "      <td>3c1bb38c-82e3-4f8d-a115-a7110ba70d05</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>WorkspaceResourceGroup</th>\n",
       "      <td>contoso77</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>TimeGenerated</th>\n",
       "      <td>2019-01-12 06:41:44</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ResourceId</th>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>SourceComputerId</th>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>CompromisedEntity</th>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table><br/><h3>ExtendedProperties:</h3><table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>0</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Alert Mode</th>\n",
       "      <td>Aggregated</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Search Query</th>\n",
       "      <td>{\"detailBladeInputs\":{\"id\":\"/subscriptions/3c1bb38c-82e3-4f8d-a115-a7110ba70d05/resourcegroups/contoso77/providers/microsoft.operationalinsights/workspaces/contoso77\",\"parameters\":{\"q\":\"SecurityEvent\\n| where EventID == 4625\\n| extend IPCustomEntity = \\\"75.10.91.22\\\"\\n| extend HostCustomEntity = Computer\\n| extend AccountCustomEntity = Account\",\"timeInterval\":{\"intervalDuration\":86400,\"intervalEnd\":\"2019-01-12T06%3A31%3A40.000Z\"}}},\"detailBlade\":\"SearchBlade\",\"displayValue\":\"SecurityEvent\\n| where EventID == 4625\\n| extend IPCustomEntity = \\\"75.10.91.22\\\"\\n| extend HostCustomEntity = Computer\\n| extend AccountCustomEntity = Account\",\"extension\":\"Microsoft_OperationsManagementSuite_Workspace\",\"kind\":\"OpenBlade\"}</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Search Query Results Overall Count</th>\n",
       "      <td>23034</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Threshold Operator</th>\n",
       "      <td>Greater Than</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Threshold Value</th>\n",
       "      <td>10000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Query Interval in Minutes</th>\n",
       "      <td>1440</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Suppression in Minutes</th>\n",
       "      <td>800</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Total Account Entities</th>\n",
       "      <td>1563</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Total IP Entities</th>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Total Host Entities</th>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table><h3>Entity counts: </h3>ip: 1, host: 1, account: 3"
      ],
      "text/plain": [
       "SecurityAlert(Unnamed: 0=0, TenantId=802d39e1-9d70-404d-832c-2de5e2478eda, StartTimeUtc=2019-0...)"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "alert_select = nbwidgets.SelectAlert(alerts=alerts, action=SecurityAlert)\n",
    "alert_select.display()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-12-19T22:39:52.652753Z",
     "start_time": "2019-12-19T22:39:52.584806Z"
    },
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "### Or a more detailed display with extracted entities"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "544eb0a357774e3a971110f493845c7e",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "VBox(children=(Text(value='', description='Filter alerts by title:', style=DescriptionStyle(description_width=…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "<hr>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Ian\\AppData\\Local\\Temp\\ipykernel_43852\\315947405.py:6: DeprecationWarning: Call to deprecated class SecurityAlert. (Replaced by Alert entity in datamodel) -- Deprecated since version 1.7.0.\n",
      "  return HTML(SecurityAlert(alert).to_html(show_entities=True))\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "\n",
       "            <h3>Alert: 'Suspicious Account Creation Detected'</h3>\n",
       "            <b>Alert_time:</b> 2019-01-15 09:15:03,\n",
       "            <b>Compr_entity:</b> MSTICALERTSWIN1,\n",
       "            <b>Alert_id:</b> self.properties['SystemAlertId']\n",
       "            <table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>45</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Unnamed: 0</th>\n",
       "      <td>45</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>TenantId</th>\n",
       "      <td>802d39e1-9d70-404d-832c-2de5e2478eda</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>StartTimeUtc</th>\n",
       "      <td>2019-01-15 09:15:03</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>EndTimeUtc</th>\n",
       "      <td>2019-01-15 09:15:03</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ProviderAlertId</th>\n",
       "      <td>526e34b6-6578-4fc0-9db6-e126b4d673f0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>SystemAlertId</th>\n",
       "      <td>2518547570966661760_526e34b6-6578-4fc0-9db6-e126b4d673f0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ProviderName</th>\n",
       "      <td>Detection</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>VendorName</th>\n",
       "      <td>Microsoft</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>AlertType</th>\n",
       "      <td>Suspicious Account Creation Detected</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>AlertName</th>\n",
       "      <td>Suspicious Account Creation Detected</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>AlertDisplayName</th>\n",
       "      <td>Suspicious Account Creation Detected</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Description</th>\n",
       "      <td>Analysis of host data on MSTICALERTSWIN1 detected creation or use of a local account adm1nistrator : this account name closely resembles a standard Windows account or group name 'administrator'. This is potentially a rogue account created by an attacker, so named in order to avoid being noticed by a human administrator.</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Severity</th>\n",
       "      <td>Medium</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>IsIncident</th>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ExtendedProperties</th>\n",
       "      <td>{'Compromised Host': 'MSTICALERTSWIN1', 'User Name': 'adm1nistrator', 'Account Session Id': '0x0', 'Suspicious Process': 'c:\\windows\\system32\\net.exe', 'Suspicious Command Line': 'net  user adm1nistrator bob_testing /add', 'Parent Process': 'c:\\windows\\system32\\cmd.exe', 'Suspicious Process Id': '0x141c', 'Suspicious Account Name': 'adm1nistrator', 'Similar To Account Name': 'administrator', 'resourceType': 'Virtual Machine', 'ServiceId': '14fa08c7-c48e-4c18-950c-8148024b4398', 'ReportingSystem': 'Azure', 'OccuringDatacenter': 'eastus'}</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Entities</th>\n",
       "      <td>[{'$id': '4', 'DnsDomain': '', 'NTDomain': '', 'HostName': 'MSTICALERTSWIN1', 'NetBiosName': 'MSTICALERTSWIN1', 'OSFamily': 'Windows', 'OSVersion': 'Windows', 'IsDomainJoined': False, 'Type': 'host'}, {'$id': '5', 'Name': 'adm1nistrator', 'Host': {'$ref': '4'}, 'Type': 'account', 'LogonId': '0x0'}, {'$id': '6', 'Directory': 'c:\\windows\\system32', 'Name': 'cmd.exe', 'Type': 'file'}, {'$id': '7', 'ProcessId': '0x165c', 'CommandLine': '', 'ImageFile': {'$ref': '6'}, 'Host': {'$ref': '4'}, 'Type': 'process'}, {'$id': '8', 'Name': 'MSTICAdmin', 'NTDomain': 'MSTICAlertsWin1', 'Sid': 'S-1-5-21-996632719-2361334927-4038480536-500', 'IsDomainJoined': False, 'Type': 'account', 'LogonId': '0x13bded7'}, {'$id': '9', 'Directory': 'c:\\windows\\system32', 'Name': 'net.exe', 'Type': 'file'}, {'$id': '10', 'ProcessId': '0x141c', 'CommandLine': 'net  user adm1nistrator bob_testing /add', 'ElevationToken': 'Default', 'CreationTimeUtc': '2019-01-15T09:15:03.3338239Z', 'ImageFile': {'$ref': '9'}, 'Account': {'$ref': '8'}, 'ParentProcess': {'$ref': '7'}, 'Host': {'$ref': '4'}, 'Type': 'process'}, {'$id': '11', 'SessionId': '0x0', 'StartTimeUtc': '2019-01-15T09:15:03.3338239Z', 'EndTimeUtc': '2019-01-15T09:15:03.3338239Z', 'Type': 'host-logon-session', 'Host': {'$ref': '4'}, 'Account': {'$ref': '5'}}]</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ConfidenceLevel</th>\n",
       "      <td>Unknown</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ConfidenceScore</th>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ExtendedLinks</th>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>WorkspaceSubscriptionId</th>\n",
       "      <td>3c1bb38c-82e3-4f8d-a115-a7110ba70d05</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>WorkspaceResourceGroup</th>\n",
       "      <td>contoso77</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>TimeGenerated</th>\n",
       "      <td>2019-01-15 09:15:08</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ResourceId</th>\n",
       "      <td>/subscriptions/40dcc8bf-0478-4f3b-b275-ed0a94f2c013/resourceGroups/ASIHuntOMSWorkspaceRG/providers/Microsoft.Compute/virtualMachines/MSTICAlertsWin1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>SourceComputerId</th>\n",
       "      <td>46fe7078-61bb-4bed-9430-7ac01d91c273</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>CompromisedEntity</th>\n",
       "      <td>MSTICALERTSWIN1</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table><br/><h3>ExtendedProperties:</h3><table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>0</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Compromised Host</th>\n",
       "      <td>MSTICALERTSWIN1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>User Name</th>\n",
       "      <td>adm1nistrator</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Account Session Id</th>\n",
       "      <td>0x0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Suspicious Process</th>\n",
       "      <td>c:\\windows\\system32\\net.exe</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Suspicious Command Line</th>\n",
       "      <td>net  user adm1nistrator bob_testing /add</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Parent Process</th>\n",
       "      <td>c:\\windows\\system32\\cmd.exe</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Suspicious Process Id</th>\n",
       "      <td>0x141c</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Suspicious Account Name</th>\n",
       "      <td>adm1nistrator</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Similar To Account Name</th>\n",
       "      <td>administrator</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>resourceType</th>\n",
       "      <td>Virtual Machine</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ServiceId</th>\n",
       "      <td>14fa08c7-c48e-4c18-950c-8148024b4398</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ReportingSystem</th>\n",
       "      <td>Azure</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>OccuringDatacenter</th>\n",
       "      <td>eastus</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table><br/><h3>Entities:</h3><br/>{ &#x27;HostName&#x27;: &#x27;MSTICALERTSWIN1&#x27;,,   &#x27;NetBiosName&#x27;: &#x27;MSTICALERTSWIN1&#x27;,,   &#x27;OSFamily&#x27;: &lt;OSFamily.Windows: 1&gt;,,   &#x27;TimeGenerated&#x27;: datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),,   &#x27;Type&#x27;: &#x27;host&#x27;}<br/>{ &#x27;Host&#x27;: { &#x27;HostName&#x27;: &#x27;MSTICALERTSWIN1&#x27;,,             &#x27;NetBiosName&#x27;: &#x27;MSTICALERTSWIN1&#x27;,,             &#x27;OSFamily&#x27;: &lt;OSFamily.Windows: 1&gt;,,             &#x27;TimeGenerated&#x27;: datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),,             &#x27;Type&#x27;: &#x27;host&#x27;},,   &#x27;LogonId&#x27;: &#x27;0x0&#x27;,,   &#x27;Name&#x27;: &#x27;adm1nistrator&#x27;,,   &#x27;TimeGenerated&#x27;: datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),,   &#x27;Type&#x27;: &#x27;account&#x27;}<br/>{ &#x27;Directory&#x27;: &#x27;c:\\\\windows\\\\system32&#x27;,,   &#x27;FullPath&#x27;: &#x27;c:\\\\windows\\\\system32\\\\cmd.exe&#x27;,,   &#x27;Name&#x27;: &#x27;cmd.exe&#x27;,,   &#x27;OSFamily&#x27;: &lt;OSFamily.Windows: 1&gt;,,   &#x27;PathSeparator&#x27;: &#x27;\\\\&#x27;,,   &#x27;TimeGenerated&#x27;: datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),,   &#x27;Type&#x27;: &#x27;file&#x27;}<br/>{ &#x27;CreationTimeUtc&#x27;: datetime.datetime(1, 1, 1, 0, 0),,   &#x27;Host&#x27;: { &#x27;HostName&#x27;: &#x27;MSTICALERTSWIN1&#x27;,,             &#x27;NetBiosName&#x27;: &#x27;MSTICALERTSWIN1&#x27;,,             &#x27;OSFamily&#x27;: &lt;OSFamily.Windows: 1&gt;,,             &#x27;TimeGenerated&#x27;: datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),,             &#x27;Type&#x27;: &#x27;host&#x27;},,   &#x27;ImageFile&#x27;: { &#x27;Directory&#x27;: &#x27;c:\\\\windows\\\\system32&#x27;,,                  &#x27;FullPath&#x27;: &#x27;c:\\\\windows\\\\system32\\\\cmd.exe&#x27;,,                  &#x27;Name&#x27;: &#x27;cmd.exe&#x27;,,                  &#x27;OSFamily&#x27;: &lt;OSFamily.Windows: 1&gt;,,                  &#x27;PathSeparator&#x27;: &#x27;\\\\&#x27;,,                  &#x27;TimeGenerated&#x27;: datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),,                  &#x27;Type&#x27;: &#x27;file&#x27;},,   &#x27;ProcessId&#x27;: &#x27;0x165c&#x27;,,   &#x27;TimeGenerated&#x27;: datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),,   &#x27;Type&#x27;: &#x27;process&#x27;}<br/>{ &#x27;LogonId&#x27;: &#x27;0x13bded7&#x27;,,   &#x27;NTDomain&#x27;: &#x27;MSTICAlertsWin1&#x27;,,   &#x27;Name&#x27;: &#x27;MSTICAdmin&#x27;,,   &#x27;Sid&#x27;: &#x27;S-1-5-21-996632719-2361334927-4038480536-500&#x27;,,   &#x27;TimeGenerated&#x27;: datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),,   &#x27;Type&#x27;: &#x27;account&#x27;}<br/>{ &#x27;Directory&#x27;: &#x27;c:\\\\windows\\\\system32&#x27;,,   &#x27;FullPath&#x27;: &#x27;c:\\\\windows\\\\system32\\\\net.exe&#x27;,,   &#x27;Name&#x27;: &#x27;net.exe&#x27;,,   &#x27;OSFamily&#x27;: &lt;OSFamily.Windows: 1&gt;,,   &#x27;PathSeparator&#x27;: &#x27;\\\\&#x27;,,   &#x27;TimeGenerated&#x27;: datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),,   &#x27;Type&#x27;: &#x27;file&#x27;}<br/>{ &#x27;Account&#x27;: { &#x27;LogonId&#x27;: &#x27;0x13bded7&#x27;,,                &#x27;NTDomain&#x27;: &#x27;MSTICAlertsWin1&#x27;,,                &#x27;Name&#x27;: &#x27;MSTICAdmin&#x27;,,                &#x27;Sid&#x27;: &#x27;S-1-5-21-996632719-2361334927-4038480536-500&#x27;,,                &#x27;TimeGenerated&#x27;: datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),,                &#x27;Type&#x27;: &#x27;account&#x27;},,   &#x27;CommandLine&#x27;: &#x27;net  user adm1nistrator bob_testing /add&#x27;,,   &#x27;CreationTimeUtc&#x27;: &#x27;2019-01-15T09:15:03.3338239Z&#x27;,,   &#x27;ElevationToken&#x27;: &#x27;Default&#x27;,,   &#x27;Host&#x27;: { &#x27;HostName&#x27;: &#x27;MSTICALERTSWIN1&#x27;,,             &#x27;NetBiosName&#x27;: &#x27;MSTICALERTSWIN1&#x27;,,             &#x27;OSFamily&#x27;: &lt;OSFamily.Windows: 1&gt;,,             &#x27;TimeGenerated&#x27;: datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),,             &#x27;Type&#x27;: &#x27;host&#x27;},,   &#x27;ImageFile&#x27;: { &#x27;Directory&#x27;: &#x27;c:\\\\windows\\\\system32&#x27;,,                  &#x27;FullPath&#x27;: &#x27;c:\\\\windows\\\\system32\\\\net.exe&#x27;,,                  &#x27;Name&#x27;: &#x27;net.exe&#x27;,,                  &#x27;OSFamily&#x27;: &lt;OSFamily.Windows: 1&gt;,,                  &#x27;PathSeparator&#x27;: &#x27;\\\\&#x27;,,                  &#x27;TimeGenerated&#x27;: datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),,                  &#x27;Type&#x27;: &#x27;file&#x27;},,   &#x27;ParentProcess&#x27;: { &#x27;CreationTimeUtc&#x27;: datetime.datetime(1, 1, 1, 0, 0),,                      &#x27;Host&#x27;: { &#x27;HostName&#x27;: &#x27;MSTICALERTSWIN1&#x27;,,                                &#x27;NetBiosName&#x27;: &#x27;MSTICALERTSWIN1&#x27;,,                                &#x27;OSFamily&#x27;: &lt;OSFamily.Windows: 1&gt;,,                                &#x27;TimeGenerated&#x27;: datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),,                                &#x27;Type&#x27;: &#x27;host&#x27;},,                      &#x27;ImageFile&#x27;: { &#x27;Directory&#x27;: &#x27;c:\\\\windows\\\\system32&#x27;,,                                     &#x27;FullPath&#x27;: &#x27;c:\\\\windows\\\\system32\\\\cmd.exe&#x27;,,                                     &#x27;Name&#x27;: &#x27;cmd.exe&#x27;,,                                     &#x27;OSFamily&#x27;: &lt;OSFamily.Windows: 1&gt;,,                                     &#x27;PathSeparator&#x27;: &#x27;\\\\&#x27;,,                                     &#x27;TimeGenerated&#x27;: datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),,                                     &#x27;Type&#x27;: &#x27;file&#x27;},,                      &#x27;ProcessId&#x27;: &#x27;0x165c&#x27;,,                      &#x27;TimeGenerated&#x27;: datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),,                      &#x27;Type&#x27;: &#x27;process&#x27;},,   &#x27;ProcessId&#x27;: &#x27;0x141c&#x27;,,   &#x27;TimeGenerated&#x27;: datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),,   &#x27;Type&#x27;: &#x27;process&#x27;}<br/>{ &#x27;Account&#x27;: { &#x27;Host&#x27;: { &#x27;HostName&#x27;: &#x27;MSTICALERTSWIN1&#x27;,,                          &#x27;NetBiosName&#x27;: &#x27;MSTICALERTSWIN1&#x27;,,                          &#x27;OSFamily&#x27;: &lt;OSFamily.Windows: 1&gt;,,                          &#x27;TimeGenerated&#x27;: datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),,                          &#x27;Type&#x27;: &#x27;host&#x27;},,                &#x27;LogonId&#x27;: &#x27;0x0&#x27;,,                &#x27;Name&#x27;: &#x27;adm1nistrator&#x27;,,                &#x27;TimeGenerated&#x27;: datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),,                &#x27;Type&#x27;: &#x27;account&#x27;},,   &#x27;EndTimeUtc&#x27;: &#x27;2019-01-15T09:15:03.3338239Z&#x27;,,   &#x27;Host&#x27;: { &#x27;HostName&#x27;: &#x27;MSTICALERTSWIN1&#x27;,,             &#x27;NetBiosName&#x27;: &#x27;MSTICALERTSWIN1&#x27;,,             &#x27;OSFamily&#x27;: &lt;OSFamily.Windows: 1&gt;,,             &#x27;TimeGenerated&#x27;: datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),,             &#x27;Type&#x27;: &#x27;host&#x27;},,   &#x27;SessionId&#x27;: &#x27;0x0&#x27;,,   &#x27;StartTimeUtc&#x27;: &#x27;2019-01-15T09:15:03.3338239Z&#x27;,,   &#x27;TimeGenerated&#x27;: datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),,   &#x27;Type&#x27;: &#x27;host-logon-session&#x27;}"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from IPython.display import HTML\n",
    "security_alert = None\n",
    "\n",
    "# create a function to get the displayable object\n",
    "def alert_with_entities(alert):\n",
    "    return HTML(SecurityAlert(alert).to_html(show_entities=True))\n",
    "                \n",
    "alert_select = nbwidgets.SelectAlert(alerts=alerts.query('CompromisedEntity == \"MSTICALERTSWIN1\"'), \n",
    "                                     action=alert_with_entities)\n",
    "display(Markdown('### Or a more detailed display with extracted entities'))\n",
    "alert_select"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='SelectItem'></a>[Contents](#contents)\n",
    "## SelectItem\n",
    "\n",
    "Similar to AlertSelector but simpler and allows you to use any list or dictionary of items.\n",
    "\n",
    "```\n",
    "Selection list from list or dict.\n",
    "\n",
    "Attributes:\n",
    "    value : The selected value.\n",
    "Init docstring:\n",
    "Select an item from a list or dict.\n",
    "\n",
    "Parameters\n",
    "----------\n",
    "description : str, optional\n",
    "    The widget label to display (the default is None)\n",
    "item_list : List[str], optional\n",
    "    A `list` of items to select from (the default is None)\n",
    "item_dict : Mapping[str, str], optional\n",
    "    A `dict` of items to select from. When using `item_dict`\n",
    "    the keys are displayed as the selectable items and value\n",
    "    corresponding to the selected key is set as the `value`\n",
    "    property.\n",
    "    (the default is None)\n",
    "action : Callable[..., None], optional\n",
    "    function to call when item selected (passed a single\n",
    "    parameter - the value of the currently selected item)\n",
    "    (the default is None)\n",
    "auto_display : bool, optional\n",
    "    Whether to display on instantiation (the default is False)\n",
    "height : str, optional\n",
    "    Selection list height (the default is '100px')\n",
    "width : str, optional\n",
    "    Selection list width (the default is '50%')\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-12-19T22:40:00.225872Z",
     "start_time": "2019-12-19T22:40:00.198893Z"
    }
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Ian\\AppData\\Local\\Temp\\ipykernel_43852\\2926117687.py:2: DeprecationWarning: Call to deprecated class SecurityAlert. (Replaced by Alert entity in datamodel) -- Deprecated since version 1.7.0.\n",
      "  security_alert = SecurityAlert(alert_select.selected_alert)\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "57a8e800d29e4a709ba2d9daaf8d1deb",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "VBox(children=(Text(value='host', description='Filter:', style=DescriptionStyle(description_width='initial')),…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "<hr>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "<h3>host</h3>{&nbsp;'HostName':&nbsp;'MSTICALERTSWIN1',<br>&nbsp;&nbsp;'NetBiosName':&nbsp;'MSTICALERTSWIN1',<br>&nbsp;&nbsp;'OSFamily':&nbsp;<OSFamily.Windows:&nbsp;1>,<br>&nbsp;&nbsp;'TimeGenerated':&nbsp;datetime.datetime(2022,&nbsp;3,&nbsp;15,&nbsp;20,&nbsp;30,&nbsp;12,&nbsp;642220),<br>&nbsp;&nbsp;'Type':&nbsp;'host'}"
      ],
      "text/plain": [
       "Host(HostName=MSTICALERTSWIN1, NetBiosName=MSTICALERTSWIN1, OSFamily=OSFamily.Windows...)"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# extract the entities from the previously selected alert\n",
    "security_alert = SecurityAlert(alert_select.selected_alert)\n",
    "if security_alert is None:\n",
    "    security_alert = SecurityAlert(alerts.iloc[1])\n",
    "ent_dict = {ent['Type']:ent for ent in security_alert.entities}\n",
    "\n",
    "# from IPython.display import HTML\n",
    "\n",
    "# # create a display function for the entities\n",
    "# def entity_to_html(entity):\n",
    "#     e_text = str(entity)\n",
    "#     e_type = entity.Type\n",
    "#     e_text = e_text.replace(\"\\n\", \"<br>\").replace(\" \", \"&nbsp;\")\n",
    "#     return HTML(f\"<h3>{e_type}</h3>{e_text}\")\n",
    "    \n",
    "nbwidgets.SelectItem(item_dict=ent_dict,\n",
    "                       description='Select an item',\n",
    "                       action=lambda x: x,\n",
    "                       auto_display=True);\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='GetEnvironmentKey'></a>[Contents](#contents)\n",
    "## GetEnvironmentKey\n",
    "Get editable value of environment variable. Common use would be retrieving an API key from your environment or allowing you to paste in a value if the environment key isn't set.\n",
    "\n",
    "Note setting the variable only persists in the python kernel process running at the time. So you can retrieve it later in the notebook but not in other processes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-12-19T22:43:18.702480Z",
     "start_time": "2019-12-19T22:43:18.680497Z"
    },
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "76bbbae36b054f0297a29ee8c26a696a",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(Text(value='C:\\\\Users\\\\Ian', description='Enter the value: ', layout=Layout(width='50%'), style…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "nbwidgets.GetEnvironmentKey(env_var='userprofile', auto_display=True);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='SelectSubset'></a>[Contents](#contents)\n",
    "## SelectSubset\n",
    "Allows you to select one or multiple items from a list to populate an output set.\n",
    "\n",
    "```\n",
    "Class to select a subset from an input list.\n",
    "\n",
    "    Attributes\n",
    "    ----------\n",
    "    selected_values : List[Any]\n",
    "        The selected item values.\n",
    "    selected_items : List[Any]\n",
    "        The selected items label and value\n",
    "        \n",
    "Init docstring:\n",
    "Create instance of SelectSubset widget.\n",
    "\n",
    "Parameters\n",
    "----------\n",
    "source_items : Union[Dict[str, str], List[Any]]\n",
    "    List of source items - either a dictionary(label, value),\n",
    "    a simple list or\n",
    "    a list of (label, value) tuples.\n",
    "default_selected : Union[Dict[str, str], List[Any]]\n",
    "    Populate the selected list with values - either\n",
    "    a dictionary(label, value),\n",
    "    a simple list or\n",
    "    a list of (label, value) tuples.\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-12-19T22:52:10.297759Z",
     "start_time": "2019-12-19T22:52:10.252790Z"
    }
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "c5c37e8b5d75487bad599809008f4583",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "VBox(children=(Text(value='', description='Filter:', style=DescriptionStyle(description_width='initial')), HBo…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Simple list\n",
    "items = list(alerts[\"AlertName\"].values)\n",
    "sel_sub = nbwidgets.SelectSubset(source_items=items)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-12-19T22:52:37.922930Z",
     "start_time": "2019-12-19T22:52:37.880962Z"
    },
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "24055d94f2b3478491c0ef06ef80f2ec",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "VBox(children=(Text(value='', description='Filter:', style=DescriptionStyle(description_width='initial')), HBo…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Label/Value pair items with a a subset of pre-selected items\n",
    "items = {v: k for k, v in alerts[\"AlertName\"].to_dict().items()}\n",
    "pre_selected = {v: k for k, v in alerts[\"AlertName\"].to_dict().items() if \"commandline\" in v}\n",
    "sel_sub = nbwidgets.SelectSubset(source_items=items, default_selected=pre_selected)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-09-02T23:54:08.581230Z",
     "start_time": "2019-09-02T23:54:08.577235Z"
    },
    "scrolled": true,
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Values: [79, 109, 83] \n",
      "\n",
      "Items: [('Detected suspicious commandline arguments', 79), ('Detected suspicious commandline used to start all executables in a directory', 109), ('Detected suspicious credentials in commandline', 83)]\n"
     ]
    }
   ],
   "source": [
    "print(\"Values:\", sel_sub.selected_values, \"\\n\")\n",
    "print(\"Items:\", sel_sub.selected_items)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Progress Indicator"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-12-19T23:04:17.717178Z",
     "start_time": "2019-12-19T23:04:14.399755Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "806a520c945d4f1884efa8cdb37af174",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, bar_style='info', description='Progress:', layout=Layout(visibility='visib…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "a182ee6d8e0c49b6a0df5f72181810f4",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, bar_style='info', description='Progress:', layout=Layout(visibility='visib…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Volume goes to eleven!\n"
     ]
    }
   ],
   "source": [
    "from time import sleep\n",
    "progress = nbwidgets.Progress(completed_len=2000)\n",
    "for i in range(0, 2100, 100):\n",
    "    progress.update_progress(new_total=i)\n",
    "    sleep(0.1)\n",
    "    \n",
    "inc_progress = nbwidgets.Progress(completed_len=10)\n",
    "for i in range(0, 11):\n",
    "    inc_progress.update_progress(delta=1)\n",
    "    sleep(0.1)\n",
    "print(\"Volume goes to eleven!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Logon Display\n",
    "Display logon details for a Windows or Linux logon"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "710b36a6e98e4fb78a6d231c9d92da7f",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "VBox(children=(Text(value='MSTICAlertsWin1/MSTICAdmin   (2019-01-15 05:15:02.980)', description='Filter:', sty…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "<hr>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "\n",
       "        <style>\n",
       "            .table_logon {border-collapse: collapse; width: 50%;}\n",
       "            .cell_logon {border: 1px solid #ddd !important;\n",
       "                text-align: left !important; padding: 15px !important;}\n",
       "        </style>\n",
       "        <table class='table_logon'><tr class='cell_logon'><td class='cell_logon'><b>Account: </b>MSTICAdmin<br><b>Account Domain: </b>MSTICAlertsWin1<br><b>Logon Time: </b>2019-01-15 05:15:02.980<br><b>Logon type: </b>4(Batch)<br><b>User Id/SID: </b>S-1-5-21-996632719-2361334927-4038480536-500<br>&nbsp;&nbsp;SID S-1-5-21-996632719-2361334927-4038480536-500 is administrator<br>&nbsp;&nbsp;SID S-1-5-21-996632719-2361334927-4038480536-500 is local machine or domain account<br><br><b>Subject (source) account: </b>WORKGROUP/MSTICAlertsWin1$<br><b>Logon process: </b>Advapi  <br><b>Authentication: </b>Negotiate<br><b>Source IpAddress: </b>-<br><b>Source Host: </b>MSTICAlertsWin1<br><b>Logon status: </b>nan<br></td></tr></table>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "win_logons = pd.read_csv(\"data/host_logons.csv\")\n",
    "user_dict = win_logons.apply(lambda x: f\"{x.TargetDomainName}/{x.TargetUserName}   ({x.TimeGenerated})\", axis=1).to_dict()\n",
    "user_dict = {v: k for k, v in user_dict.items()}\n",
    "\n",
    "from msticpy.vis.nbdisplay import format_logon\n",
    "# create a display function for the entities\n",
    "def disp_logon(index):\n",
    "    print\n",
    "    logons = win_logons[win_logons.index == index]\n",
    "    return format_logon(logons)\n",
    "    \n",
    "acct_select = nbwidgets.SelectItem(item_dict=user_dict,\n",
    "                       description='Select an item',\n",
    "                       action=disp_logon,\n",
    "                       auto_display=True);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Display a list of logons"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "        <style>\n",
       "            .table_logon {border-collapse: collapse; width: 50%;}\n",
       "            .cell_logon {border: 1px solid #ddd !important;\n",
       "                text-align: left !important; padding: 15px !important;}\n",
       "        </style>\n",
       "        <table class='table_logon'><tr class='cell_logon'><td class='cell_logon'><b>Account: </b>MSTICAdmin<br><b>Account Domain: </b>MSTICAlertsWin1<br><b>Logon Time: </b>2019-01-15 05:15:02.980<br><b>Logon type: </b>4(Batch)<br><b>User Id/SID: </b>S-1-5-21-996632719-2361334927-4038480536-500<br>&nbsp;&nbsp;SID S-1-5-21-996632719-2361334927-4038480536-500 is administrator<br>&nbsp;&nbsp;SID S-1-5-21-996632719-2361334927-4038480536-500 is local machine or domain account<br><br><b>Subject (source) account: </b>WORKGROUP/MSTICAlertsWin1$<br><b>Logon process: </b>Advapi  <br><b>Authentication: </b>Negotiate<br><b>Source IpAddress: </b>-<br><b>Source Host: </b>MSTICAlertsWin1<br><b>Logon status: </b>nan<br></td></tr><tr class='cell_logon'><td class='cell_logon'><b>Account: </b>SYSTEM<br><b>Account Domain: </b>NT AUTHORITY<br><b>Logon Time: </b>2019-01-15 05:15:04.503<br><b>Logon type: </b>5(Service)<br><b>User Id/SID: </b>S-1-5-18<br>&nbsp;&nbsp;SID S-1-5-18 is LOCAL_SYSTEM<br><br><b>Subject (source) account: </b>WORKGROUP/MSTICAlertsWin1$<br><b>Logon process: </b>Advapi  <br><b>Authentication: </b>Negotiate<br><b>Source IpAddress: </b>-<br><b>Source Host: </b>-<br><b>Logon status: </b>nan<br></td></tr><tr class='cell_logon'><td class='cell_logon'><b>Account: </b>adm1nistrator<br><b>Account Domain: </b>MSTICAlertsWin1<br><b>Logon Time: </b>2019-01-15 05:15:06.363<br><b>Logon type: </b>3(Network)<br><b>User Id/SID: </b>S-1-5-21-996632719-2361334927-4038480536-1066<br>&nbsp;&nbsp;SID S-1-5-21-996632719-2361334927-4038480536-1066 is local machine or domain account<br><br><b>Subject (source) account: </b>-/-<br><b>Logon process: </b>NtLmSsp <br><b>Authentication: </b>NTLM<br><b>Source IpAddress: </b>fe80::38dc:e4a9:61bd:b458<br><b>Source Host: </b>MSTICAlertsWin1<br><b>Logon status: </b>nan<br></td></tr><tr class='cell_logon'><td class='cell_logon'><b>Account: </b>SYSTEM<br><b>Account Domain: </b>NT AUTHORITY<br><b>Logon Time: </b>2019-01-15 05:15:10.813<br><b>Logon type: </b>5(Service)<br><b>User Id/SID: </b>S-1-5-18<br>&nbsp;&nbsp;SID S-1-5-18 is LOCAL_SYSTEM<br><br><b>Subject (source) account: </b>WORKGROUP/MSTICAlertsWin1$<br><b>Logon process: </b>Advapi  <br><b>Authentication: </b>Negotiate<br><b>Source IpAddress: </b>-<br><b>Source Host: </b>-<br><b>Logon status: </b>nan<br></td></tr><tr class='cell_logon'><td class='cell_logon'><b>Account: </b>SYSTEM<br><b>Account Domain: </b>NT AUTHORITY<br><b>Logon Time: </b>2019-01-15 05:15:14.453<br><b>Logon type: </b>5(Service)<br><b>User Id/SID: </b>S-1-5-18<br>&nbsp;&nbsp;SID S-1-5-18 is LOCAL_SYSTEM<br><br><b>Subject (source) account: </b>WORKGROUP/MSTICAlertsWin1$<br><b>Logon process: </b>Advapi  <br><b>Authentication: </b>Negotiate<br><b>Source IpAddress: </b>-<br><b>Source Host: </b>-<br><b>Logon status: </b>nan<br></td></tr></table>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# display a list of logons\n",
    "display(format_logon(win_logons.head(5)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Registered Widgets\n",
    "\n",
    "Some of the widgets (QueryTimes, GetText) can register themselves and retain\n",
    "the setting and values previously entered. This can be useful when stepping through\n",
    "a notebook since it is a common mistake to enter text in a text box and then\n",
    "execute the same cell again by mistake. This, of course, usually results in the \n",
    "widget being reset to its default state and erasing the values you just entered.\n",
    "\n",
    "If you use a registered widget and then create a new copy of the widget with identical\n",
    "parameters it will look in the registry for a previous copy of itself and auto-populate\n",
    "it's values with the previous-entered ones.\n",
    "\n",
    "Registered widgets can also read their default values from notebook variables - this\n",
    "is mainly useful with notebooks that are programmatically supplied with \n",
    "parameters and executed with something like Papermill.\n",
    "\n",
    "Several of the additional parameters available in RegisteredWidgets init are\n",
    "for internal use by widgets but three are usable by users:\n",
    "```\n",
    "        Parameters\n",
    "        ----------\n",
    "        nb_params : Optional[Dict[str, str]], optional\n",
    "            A dictionary of attribute names and global variables. If the variable\n",
    "            exists in the global namespace it will be used to populate the\n",
    "            corresponding widget attribute. This is only done if the widget\n",
    "            attribute currently has no value (i.e. restoring a value from\n",
    "            the registry takes priority over this),\n",
    "            by default None\n",
    "        ns : Dict[str, Any], optional\n",
    "            Namespace to look for global variables, by default None\n",
    "        register : bool\n",
    "            Do not register the widget or retrieve values from previously-\n",
    "            registered instance.\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "        Initialize a registered widget.\n",
      "\n",
      "        Parameters\n",
      "        ----------\n",
      "        id_vals : Optional[List[Any]], optional\n",
      "            The list of parameter values to use to identify this widget instance,\n",
      "            by default None\n",
      "        val_attrs : Optional[List[str]], optional\n",
      "            The names of the attributes to persist in the registry\n",
      "            and recall, by default [\"value\"]\n",
      "        nb_params : Optional[Dict[str, str]], optional\n",
      "            A dictionary of attribute names and global variables. If the variable\n",
      "            exists in the global namespace it will be used to populate the\n",
      "            corresponding widget attribute. This is only done if the widget\n",
      "            attribute currently has no value (i.e. restoring a value from\n",
      "            the registry takes priority over this),\n",
      "            by default None\n",
      "        name_space : Dict[str, Any], optional\n",
      "            Namespace to look for global variables, by default None\n",
      "        register : bool\n",
      "            Do not register the widget or retrieve values from previously-\n",
      "            registered instance.\n",
      "\n",
      "        \n"
     ]
    }
   ],
   "source": [
    "print(nbwidgets.RegisteredWidget.__init__.__doc__)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "59b66341409d4a8f8f4c6a92567fbc16",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Text(value='Ian', description='Enter your name', layout=Layout(width='50%'), style=DescriptionStyle(descriptio…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "mem_text = nbwidgets.GetText(prompt=\"Enter your name\")\n",
    "\n",
    "# we insert a value here to mimic typing something in the text box\n",
    "mem_text._value = \"Ian\"\n",
    "mem_text"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When we re-execute the cell or use the same widget with identical arguments\n",
    "the value is populated from the registry cache"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "cf26032317564441a5158d863fd6648e",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Text(value='Ian', description='Enter your name', layout=Layout(width='50%'), style=DescriptionStyle(descriptio…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "mem_text = nbwidgets.GetText(prompt=\"Enter your name\")\n",
    "mem_text"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### QueryTime also supports registration"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "e240234b9bc740e6b5927ea7ed1e21db",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "VBox(children=(HTML(value='<h4>Set query time boundaries</h4>'), HBox(children=(DatePicker(value=datetime.date…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from datetime import datetime, timedelta\n",
    "q_times = nbwidgets.QueryTime(auto_display=True, max_before=12, max_after=2, units=\"day\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [],
   "source": [
    "# mimic setting values in the control (these don't update the display)\n",
    "q_times.origin_time = datetime.utcnow() - timedelta(5)\n",
    "q_times.before = 3\n",
    "q_times.after = 5"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note the origin, before and after have all been copied from the previous instance"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "48db5e7718c74097a23748e09309be38",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "VBox(children=(HTML(value='<h4>Set query time boundaries</h4>'), HBox(children=(DatePicker(value=datetime.date…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "q_times = nbwidgets.QueryTime(auto_display=True, max_before=12, max_after=2, units=\"day\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### To skip registration add the parameter `register=False`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "8a710a5a6ec7496385d8a2877e677075",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "VBox(children=(HTML(value='<h4>Set query time boundaries</h4>'), HBox(children=(DatePicker(value=datetime.date…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "q_times = nbwidgets.QueryTime(auto_display=True, max_before=12, max_after=2, units=\"day\", register=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Using notebook parameters to populate RegisteredWidgets"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "bdf6040a423e467d95813e5a398986cd",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Text(value='', description='enter your real name', layout=Layout(width='50%'), style=DescriptionStyle(descript…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# This might be defined in a parameter cell at the beginning of the noteboook\n",
    "my_name = \"The other Ian\"\n",
    "\n",
    "my_text = nbwidgets.GetText(prompt=\"enter your real name\", nb_params={\"_value\": \"my_name\"}, ns=globals())\n",
    "my_text"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Multi-Option buttons with async wait\n",
    "This widget is pretty simple on the surface but has some useful features\n",
    "for waiting for user input.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "e5223807b7b64fb6a6b38a89bacd8543",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "VBox(children=(Label(value='Do you really want to do this?'), HBox(children=(Button(description='Confirm', sty…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "opt = nbwidgets.OptionButtons(\n",
    "    description=\"Do you really want to do this?\",\n",
    "    buttons=[\"Confirm\", \"Skip\", \"Cancel\"]\n",
    ")\n",
    "\n",
    "# Displaying the widget works as expected\n",
    "# and sets `widget.value` to the last chosen button value.\n",
    "opt"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Using OptionButtons to wait until an option is chosen (or timeout expires)\n",
    "Option buttons uses an asynchronous event loop to track both the button\n",
    "state and the timeout simultaneously.\n",
    "\n",
    "Because this requires the use of asynchronous code you must do the following\n",
    "- call *widget*`.display_async()` method rather than just `display()` or using the auto-display functionality of Jupyter\n",
    "- prefix this call with `await` - this tells IPython/Jupyter that you are executing asynchronous code and that it needs\n",
    "  to wait until this call has completed before continuing with cell execution. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "2366fca93e2b4945bb9dad251deade1b",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "VBox(children=(Label(value='Continue?'), HBox(children=(Button(description='Yes', style=ButtonStyle()), Button…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Using display_async will run the widget with a visible\n",
    "# timer. As soon as one option is chosen, that remains as the value\n",
    "# of the value of the widget.value property.\n",
    "opt = nbwidgets.OptionButtons(description=\"Continue?\", timeout=10)\n",
    "await opt.display_async()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> **Note**\n",
    "> Awaiting the OptionButtons control does not pause the notebook execution.\n",
    "> This is a capability that we are still working on."
   ]
  }
 ],
 "metadata": {
  "hide_input": false,
  "interpreter": {
   "hash": "2bc37074a50de3994d4ebdf9197e864a43c9c15c9793b7f9f3363bcff9457253"
  },
  "kernelspec": {
   "display_name": "Python (msticpy)",
   "language": "python",
   "name": "msticpy"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  },
  "latex_envs": {
   "LaTeX_envs_menu_present": true,
   "autoclose": false,
   "autocomplete": true,
   "bibliofile": "biblio.bib",
   "cite_by": "apalike",
   "current_citInitial": 1,
   "eqLabelWithNumbers": true,
   "eqNumInitial": 1,
   "hotkeys": {
    "equation": "Ctrl-E",
    "itemize": "Ctrl-I"
   },
   "labels_anchors": false,
   "latex_user_defs": false,
   "report_style_numbering": false,
   "user_envs_cfg": false
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": false,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  },
  "widgets": {
   "application/vnd.jupyter.widget-state+json": {
    "state": {},
    "version_major": 2,
    "version_minor": 0
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
